<!--
 * @Author: wjk
 * @Date: 2020-08-19 10:51:37
 * @LastEditors: wjk
 * @LastEditTime: 2020-10-19 17:01:02
 * @description: 验证码数字倒计时
-->
<template>
  <view class="virify-text" @click="sendMsg">
    {{ verifyText }}
  </view>
</template>
<script>
import './index.scss'
export default {
  name: 'VerifyTime',
  props: {
    title: { type: String, default: '获取验证码' },
    immediate: { type: Boolean, default: false },
    reSendTime: { type: Number, default: 60 },
    reSendText: { type: String, default: '重新发送' }
  },
  data() {
    return {
      verifyText: '',
      dealyTime: 0,
      timer: null
    }
  },
  created() {
    this.verifyText = this.title
  },
  mounted() {
    if (this.immediate) {
      setTimeout(() => {
        this.sendMsg()
      }, 100)
    }
  },
  methods: {
    sendMsg() {
      if (this.verifyText !== this.reSendText && this.verifyText !== this.title) {
        return
      }
      this.$emit('sendMsg', true)
      this.dealyTime = this.reSendTime
      this.verifyText = this.dealyTime + 's后重试'
      this.timer = setInterval(() => {
        this.dealyTime--
        this.verifyText = this.dealyTime + 's后重试'
        if (this.dealyTime <= 0) {
          clearInterval(this.timer)
          this.verifyText = this.reSendText
          this.$emit('sendMsg', false)
        }
      }, 1000)
    }
  }
}
</script>
